package com.daqian.chance.common.base;

import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.ParameterizedType;

/**
 * @author daqian
 * @date 2019/7/9 15:46
 */
@Data
public abstract class BaseDTO<E> {
    /**
     * 页码
     */
    private Integer pageNum = 1;
    /**
     * 分页大小
     */
    private Integer pageSize = 10;

    /**
     * 转换成实体类
     * @return E
     * @author daqian
     */
    public E convertToEntity() {
        E entity;
        try {
            // 通过反射获取model的真实类型
            ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
            Class<E> clazz = (Class<E>) pt.getActualTypeArguments()[0];
            // 通过反射创建model的实例
            entity = clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        BeanUtils.copyProperties(this, entity);
        return entity;
    }

    /**
     * 将DTO转换成实体类
     * @return E
     * @author daqian
     */
    public E convertToEntity(RunnableFun<E> r) {
        E entity = this.convertToEntity();
        r.run(entity);
        return entity;
    }

    public interface RunnableFun<E> {
        void run(E s);
    }
}
